use ggez::{glam::Vec2, Context, graphics, mint::Point2};
use rand::Rng;



pub struct Particle {
    location: Vec2,
    velocity: Vec2,
    acceleration: Vec2,

    angle: f32,
    a_velocity: f32,

    size: f32,
    mass: f32,
    
    lifespan: f32
}

impl Particle {
    pub fn new(location: Vec2) -> Particle {
        let mut rng = rand::thread_rng();
        let velocity = Vec2{x: rng.gen_range(-1.0..1.0), y: rng.gen_range(0.0..2.0)};
        let acceleration = Vec2{x: 0.0, y: 0.05};
        let angle = 0.0;
        let a_velocity = 0.0;
        let size = rng.gen_range(6.0..15.0);
        let mass = size*size*size;
        let lifespan = 1.0;
        Particle { location, velocity, acceleration, angle, a_velocity, size, mass, lifespan}
    }

    pub fn is_dead(&self) -> bool {
        if self.lifespan <= 0.0 {
            true
        } else {
            false
        }
    }

    pub fn get_mass(&self) -> f32 {
        self.mass
    }

    pub fn apply_force(&mut self, force: Vec2) -> () {
        self.acceleration += force;
    }

    pub fn update(&mut self) -> () {
        self.acceleration /= self.mass;
        self.velocity += self.acceleration;
        self.location += self.velocity;
        self.lifespan -= 0.01;
        self.acceleration *= 0.0;

        self.a_velocity = self.velocity.x*0.05;
        self.angle += self.a_velocity;
    }

    pub fn display(&self, ctx: &mut Context, canvas : &mut graphics::Canvas) -> () {

        let polygon = graphics::Mesh::new_polygon(
            ctx, 
            graphics::DrawMode::fill(), 
            &[Point2{x: 0.0, y: -3.0*self.size}, Point2{x: 2.0*self.size, y: 3.0*self.size}, Point2{x: 0.0, y: 0.0}, Point2{x: -2.0*self.size, y: 3.0*self.size}], 
            graphics::Color::new(0.7, 0.7, 0.7, self.lifespan)).unwrap();
        canvas.draw(&polygon, graphics::DrawParam::default().dest(self.location).rotation(self.angle)); 

        let polygon = graphics::Mesh::new_polygon(
            ctx, 
            graphics::DrawMode::stroke(2.0), 
            &[Point2{x: 0.0, y: -3.0*self.size}, Point2{x: 2.0*self.size, y: 3.0*self.size}, Point2{x: 0.0, y: 0.0}, Point2{x: -2.0*self.size, y: 3.0*self.size}], 
            graphics::Color::new(0.0, 0.0, 0.0, self.lifespan)).unwrap();
        canvas.draw(&polygon, graphics::DrawParam::default().dest(self.location).rotation(self.angle)); 



    }
}